// 引入 express 模块用于创建路由
import koaRouter from 'koa-router';
// 加密
const bcrypt = require('bcryptjs')

// 权限校验
import jwt from 'jsonwebtoken';
const { PRIVITE_KEY, EXPIRESD } = require('../token/confirm')
const { paramsquery, register, updataUserInfo } = require('../mysql/model/public');
const vertoken = require('../token/token_vertify')

// 创建路由
const publicRouter = new koaRouter();

publicRouter.post('/public/login', async (ctx, next) => {
    const { userName, passWord } = ctx.request.body;

    // 账号密码是否为空
    if (!userName || !passWord) {
        ctx.response.body = {
            message: '账号或密码不得为空',
            code: 400,
            data: {}
        }
    } else {
        // 校验：用户是否存在
        let isExist = await paramsquery(userName)
        // 查询失败
        if (isExist.status === 400) {
            ctx.response.body = isExist
            return
        }

        // 校验用户是否存在
        if (isExist.data.length === 0) {
            ctx.response.body = { code: 400, msg: '用户不存在' }
            return
        }

        // 密码校验 + 生成Token
        const resp = await bcrypt.compare(passWord, isExist.data[0].passWord);

        if (!resp) {
            ctx.response.body = { code: 400, msg: '账号或密码输入错误' }
            return
        } else {
            let obj = {
                userName: userName,
                type: 'koa-jwt',
                ctime: new Date().getTime()
            }

            // 生成Token
            const token = jwt.sign(obj, PRIVITE_KEY, { expiresIn: EXPIRESD })
            let userInfo = isExist.data[0]
            delete userInfo.passWord
            ctx.response.body = { code: 200, msg: '登录成功', token, data: userInfo }
        }
        await next();
        
    }
})

publicRouter.post('/public/register', async (ctx,next) => {
    let { userName, passWord } = ctx.request.body
    // 校验：用户是否存在
    let isExist = await paramsquery(userName)
    
    // 查询失败
    if (isExist.status === 400) {
        ctx.response.body = isExist
        return
    }

    // 校验用户是否存在
    if (isExist.data.length !== 0) {
        ctx.response.body = { code: 400, msg: '用户已存在' }
        return
    }
    
    //生成salt的迭代次数
    const saltRounds = 10;
    //随机生成salt
    const salt = bcrypt.genSaltSync(saltRounds);
    //获取hash值
    let hash = bcrypt.hashSync(passWord, salt);
    //把hash值赋值给passWord变量
    passWord = hash;
    
    const obj = {
        userName,
        passWord,
        nickName: userName,
        createTime: new Date().getTime(),
        updataTime: new Date().getTime(),
        admin: 1
    }
    
    const results = await register(obj).catch((res: object) => {
        ctx.response.body = { code: 400, msg: '注册失败', data: res }
    })

    ctx.response.body = { code: 200, msg: '注册成功', data: results }
    
})

publicRouter.post('/public/userInfo/update', async (ctx, next) => {
    // 校验：用户是否存在
    // console.log()
    const {userName} = await vertoken(ctx.request.header.authorization)
    
    const resp = await updataUserInfo(userName, ctx.request.body).catch((err: object) => {
        ctx.response.body = {
            code: 500,
            msg: '操作失败',
            data: err
        }
    })

    // 更新之后的用户信息
    let { data: [userInfo]} = await paramsquery(userName);

    delete userInfo.passWord;

    ctx.response.body = {
        code: 200,
        msg: '操作成功',
        data: userInfo
    }
    
    
    // 查询失败
    // if (isExist.status === 400) {
    //     ctx.response.body = isExist
    //     return
    // }
})

publicRouter.post('/public/userInfo/currentDetail', async (ctx, next) => {
    // 校验：用户是否存在
    const { userName } = await vertoken(ctx.request.header.authorization)

    // 更新之后的用户信息
    let { data: [userInfo] } = await paramsquery(userName).catch((err:object) => {
        ctx.response.body = {
            code: 500,
            msg: '操作失败',
            data: err
        }
    })

    delete userInfo.passWord;

    ctx.response.body = {
        code: 200,
        msg: '操作成功',
        data: userInfo
    }


    // 查询失败
    // if (isExist.status === 400) {
    //     ctx.response.body = isExist
    //     return
    // }
})

module.exports = publicRouter